//发布订阅模式
class EventHub {
    private cache: {
        [key: string]: Array<(data: unknown) => void>
    } = {}
    on(eventName: string, fn: (data: unknown) => void) {
        this.cache[eventName] = this.cache[eventName] || []
        this.cache[eventName].push(fn)
    }
    emit(eventName: string, content?: unknown) {
        (this.cache[eventName] || []).forEach(fn => {
            fn(content)
        });
    }
    off(eventName: string, fn: (data: unknown) => void) {
        let index = indexOf(this.cache[eventName], fn)
        if (index === -1) return
        this.cache[eventName].splice(index, 1);
    }
}

export default EventHub;

function indexOf(array, item) {
    if (array === undefined) return -1;
    let i = -1;
    for (let index = 0; index < array.length; index++) {
        if (array[index] === item) {
            i = index
            break
        }
    }
    return i
}